<?php

namespace app\common\model;

use think\facade\Filesystem;
use think\facade\Request;

class Upload
{
    //文件上传方式
    const UPLOAD_COMMON = 1; //本服务器存储方式
    const UPLOAD_OSS = 2;    //OSS存储方式


    /**
     * 上传图片
     */
    public function image($params = [])
    {
        try {
            if (isset($params['file']) && !empty($params['file'])) {
                $file = $params['file'];
            } else {
                $file = request()->file('image');
            }
            $type = request()->param('type', self::UPLOAD_OSS);
            $dirName = $params['dirName']??'image';
            if (empty($type)) {
                $type = self::UPLOAD_OSS;
            }
            if (!in_array($type, [self::UPLOAD_COMMON, self::UPLOAD_OSS])) {
                return fail('请先选择上传存储方式');
            }

            if (empty($file)) {
                return fail('请选择需要上传的图片');
            }
            if ($type == self::UPLOAD_COMMON) { //存储本系统
                // 上传到本地服务器
                $savename = Filesystem::disk('public')->putFile($dirName, $file);
                $url = Request::domain() . '/storage/' . str_replace('\\', '/', $savename);
            } else {  //存储OSS系统
                $savename = Filesystem::disk('aliyun')->putFile('upload/'.$dirName, $file);
                if (!$savename) {
                    return fail('上传失败');
                }
                $endpoint = Filesystem::getDiskConfig('aliyun', 'endpoint');
                // 设置存储空间名称。
                $bucket = Filesystem::getDiskConfig('aliyun', 'bucket');
                $baseUrl = 'https://'.$bucket.'.'.$endpoint;
                $pathUrl = str_replace('\\', '/', $savename);
                $url = $baseUrl.'/'.$pathUrl;
            }

        } catch (\Exception $e) {
            return fail('上传失败：' . $e->getMessage());
        }

        return success('上传成功', [
            'url' => $url,
        ]);
    }
}
